"use client";

import * as React from "react";

import { type DropdownMenuProps } from "@radix-ui/react-dropdown-menu";

import { MarkdownPlugin } from "@platejs/markdown";
import { ArrowUpToLineIcon } from "lucide-react";
import { getEditorDOMFromHtmlString } from "platejs";
import { useEditorRef } from "platejs/react";
import { useFilePicker } from "use-file-picker";

import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuGroup,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/plate/ui/dropdown-menu";

import { ToolbarButton } from "./toolbar";

type ImportType = "html" | "markdown";

export function ImportToolbarButton(props: DropdownMenuProps) {
  const editor = useEditorRef();
  const [open, setOpen] = React.useState(false);

  const getFileNodes = (text: string, type: ImportType) =&gt; {
    if (type === "html") {
      const editorNode = getEditorDOMFromHtmlString(text);
      const nodes = editor.api.html.deserialize({
        element: editorNode,
      });

      return nodes;
    }

    if (type === "markdown") {
      return editor.getApi(MarkdownPlugin).markdown.deserialize(text);
    }

    return [];
  };

  const { openFilePicker: openMdFilePicker } = useFilePicker({
    accept: [".md", ".mdx"],
    multiple: false,
    onFilesSelected: async ({ plainFiles }) =&gt; {
      const text = await plainFiles[0].text();

      const nodes = getFileNodes(text, "markdown");

      editor.tf.insertNodes(nodes);
    },
  });

  const { openFilePicker: openHtmlFilePicker } = useFilePicker({
    accept: ["text/html"],
    multiple: false,
    onFilesSelected: async ({ plainFiles }) =&gt; {
      const text = await plainFiles[0].text();

      const nodes = getFileNodes(text, "html");

      editor.tf.insertNodes(nodes);
    },
  });

  return (
    &lt;DropdownMenu open={open} onOpenChange={setOpen} modal={false} {...props}&gt;
      &lt;DropdownMenuTrigger asChild&gt;
        &lt;ToolbarButton pressed={open} tooltip="Import" isDropdown&gt;
          &lt;ArrowUpToLineIcon className="size-4" /&gt;
        &lt;/ToolbarButton&gt;
      &lt;/DropdownMenuTrigger&gt;

      &lt;DropdownMenuContent align="start"&gt;
        &lt;DropdownMenuGroup&gt;
          &lt;DropdownMenuItem
            onSelect={() =&gt; {
              openHtmlFilePicker();
            }}
          &gt;
            Import from HTML
          &lt;/DropdownMenuItem&gt;

          &lt;DropdownMenuItem
            onSelect={() =&gt; {
              openMdFilePicker();
            }}
          &gt;
            Import from Markdown
          &lt;/DropdownMenuItem&gt;
        &lt;/DropdownMenuGroup&gt;
      &lt;/DropdownMenuContent&gt;
    &lt;/DropdownMenu&gt;
  );
}
